package com.jms.web.mvc.creator;

import com.jms.framework.beans.annotation.Component;
import com.jms.web.mvc.annotaion.PathVariable;
import com.jms.web.mvc.handler.MethodHandler;
import com.jms.web.mvc.resolver.ParamTypeConverter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class PathVariableArgumentCreator extends ArgumentCreator {
    public PathVariableArgumentCreator() {
        super(19998);
    }

    @Override
    public Object create(HttpServletRequest request, HttpServletResponse response, Parameter parameter, Object handler) {
        if (parameter.isAnnotationPresent(PathVariable.class)) {
            String value = parameter.getAnnotation(PathVariable.class).value();
            Class<?> type = parameter.getType();
            if (value != null && !"".equals(value) && handler instanceof MethodHandler) {
                MethodHandler methodHandler = (MethodHandler) handler;
                Pattern uriPattern = methodHandler.getUriPattern();
                if (uriPattern != null) {
                    List<String> pathVariableNames = methodHandler.getPathVariableNames();
                    Matcher matcher = uriPattern.matcher(request.getRequestURI());

                    if (matcher.matches()) {
                        for (int i = 0; i < pathVariableNames.size(); i++) {
                            if (pathVariableNames.get(i).equals(value)) {
                                try {
                                    String pathVariable = matcher.group(i + 1);
                                    return ParamTypeConverter.convert(type, pathVariable);
                                } catch (IllegalStateException e) {
                                    // 处理组不存在的情况
                                    return null;
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

}
